import {MangaSite} from "../MangaSite";
import {
    exists,
    getAppDirPath,
    joinPath,
    mkdir,
    readDir,
    readFile,
    toPosix,
    writeFile
} from "../../../function/fileFunc";

export namespace LocalManga {
    export interface ImgItemInfo extends MangaSite.ImgItemInfo {
    }
    export interface JsonObj {
        imgList: string[];
    }
}

export class LocalManga extends MangaSite {
    public getRelLocalDir() {
        return "local/book_" +
        this.articleInfo.book_id +
        "/article_" + this.articleInfo.article_index;
    }
    public getLocalDir() {
        return toPosix(
            joinPath(
                getAppDirPath(),
                this.getRelLocalDir()
            )
        );
    }
    public drawPage(
        img: HTMLImageElement,
        position?: MangaSite.TDrawPosition,
        showPageIndexLen?: number
    ): this {
        return this.directDrawPage(img, position);
    }
    public async getImgList(): Promise<LocalManga.ImgItemInfo[]> {
        const data = await this.getJSON();
        const obj = JSON.parse(data) as any as LocalManga.JsonObj;
        console.log(obj);
        return obj.imgList.map((item, index) => {
            return {
                imgIndex: (index + 1),
                src: item,
                type: "local",
            };
        });
    }
    protected async cacheArticleInfoJSONFile(filename: string): Promise<string> {
        const localJSONFile = this.articleInfo.origin_url;
        const fileExists = await exists(localJSONFile);
        if (fileExists) {
            const data = await readFile(localJSONFile);
            writeFile(filename, data);
            return data;
        }
        const localDir = this.getLocalDir();
        const dirExists = await exists(localDir);
        if (!dirExists) {
            console.log("创建目录:\n" + localDir);
            mkdir(localDir);
        }
        const fileList = await readDir(localDir);
        const imgList = fileList.filter((item) => {
            return /\.(png|jpg|jpeg)$/.test(item);
        }).map((item) => {
            return "akaba:///" + toPosix(joinPath(this.getRelLocalDir(), item));
        });
        const listData = JSON.stringify({
            imgList,
        });
        writeFile(filename, listData);
        return listData;
    }
    protected loadImgFromTmp(imgInfo: MangaSite.ImgItemInfo, img?: HTMLImageElement): Promise<HTMLImageElement> {
        const akabaSrc = imgInfo.src;
        return this.buildImgFrom(akabaSrc, imgInfo.type, img)
            .then((imgElm) => {
                this.imgCacheMap[imgInfo.src] = imgElm;
                return imgElm;
            });
    }
}
